package com.hll.javaee.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class ImageServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // 浏览器三秒刷新
    response.setHeader("refresh", "3");
    // 内存中创建图片
    BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = (Graphics2D) image.getGraphics(); // 获得画笔
    g.setColor(Color.white);
    g.fillRect(0, 0, 80, 20); // 画矩阵
    g.setColor(Color.BLUE);
    g.setFont(new Font(null, Font.BOLD, 20));
    g.drawString(getRandom(), 0, 20); // 填充随机数

    // 设置消息头
    response.setContentType("image/jpeg");
    response.setDateHeader("expires", -1);
    response.setHeader("Cache-Control", "no-cache"); // 取消缓冲机制
    response.setHeader("Pragma", "no-cache");

    // 写入
    ImageIO.write(image, "jpg", response.getOutputStream());
  }

  private String getRandom() {
    int len = 7; // 长度还长的话就需要改一下fillRect的width
    Random random = new Random();
    String num = random.nextInt((int) (Math.pow(10, len) - 1)) + "";
    StringBuilder stringBuffer = new StringBuilder();
    for (int i = 0; i < len - num.length(); i++) { // 没有凑齐七位就前补0
      stringBuffer.append("0");
    }
    num = stringBuffer.toString() + num;
    return num;
  }
}
